package com.mmd.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author cyq
 * @Date 2019/8/21 22:13
 * @Description
 **/
public class CookieTools {
    public CookieTools() {
    }

    public static void addCookie(HttpServletResponse response, String name, String value, int maxAge) {
        Cookie cookie = new Cookie(name, value);
        String domain = System.getProperty("domain");
        if (domain == null) {
            cookie.setDomain("linxianggou.com");
        } else {
            cookie.setDomain(domain);
        }

        cookie.setPath("/");
        if (maxAge >= 0) {
            cookie.setMaxAge(maxAge);
        }

        response.addCookie(cookie);
    }

    public static void addCookie(HttpServletResponse response, String name, String value, int maxAge, String domain) {
        Cookie cookie = new Cookie(name, value);
        if (domain == null) {
            cookie.setDomain("linxianggou.com");
        } else {
            cookie.setDomain(domain);
        }

        cookie.setPath("/");
        if (maxAge >= 0) {
            cookie.setMaxAge(maxAge);
        }

        response.addCookie(cookie);
    }

    public static void delCookie(HttpServletResponse response, String name) {
        Cookie cookie = new Cookie(name, (String) null);
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }

    public static void delCookie(HttpServletResponse response, String name, String domain) {
        Cookie cookie = new Cookie(name, (String) null);
        if (domain == null) {
            cookie.setDomain("linxianggou.com");
        } else {
            cookie.setDomain(domain);
        }

        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }

    public static Cookie getCookieByName(HttpServletRequest request, String name) {
        Map<String, Cookie> cookieMap = ReadCookieMap(request);
        if (cookieMap.containsKey(name)) {
            Cookie cookie = (Cookie) cookieMap.get(name);
            return cookie;
        } else {
            return null;
        }
    }

    public static String getCookieValueByName(HttpServletRequest request, String name) {
        Cookie cookie = getCookieByName(request, name);
        return cookie == null ? null : cookie.getValue();
    }

    private static Map<String, Cookie> ReadCookieMap(HttpServletRequest request) {
        Map<String, Cookie> cookieMap = new HashMap();
        Cookie[] cookies = request.getCookies();
        if (null != cookies) {
            Cookie[] var3 = cookies;
            int var4 = cookies.length;

            for (int var5 = 0; var5 < var4; ++var5) {
                Cookie cookie = var3[var5];
                cookieMap.put(cookie.getName(), cookie);
            }
        }

        return cookieMap;
    }
}
